package com.zy.dingdong.util;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PictureUtil {
    public static final String APP_NAME="com.dong.yunchat";
    public static final int CAPTURE_PERMISSION = 1;
    public static final int PICTURE_LIB_PERMISSION = 0;
    public static final int FROM_CAMERA=101;
    public static final int FROM_PICTURE_LIB=102;
    public static final int HORIZONTAL_PICTURE=201;
    public static final int VERTICAL_PICTURE=202;
    public static final int SQUARE_PICTURE=203;
    private static final String TAG = "HELLO";
    private Activity activity;
    private File pictureFile;
    private Uri pictureUri;

    public PictureUtil(Activity activity){
        this.activity = activity;
    }

    public Uri getPictureUri(){
        return pictureUri;
    }

    public File getPictureFile(){
        return pictureFile;
    }
    public void setPictureFile(File file){
        this.pictureFile=file;
    }

    //打开相册
    public void openPictureLib() {
        //检查权限
        if(ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            //从相册选取图片
            openAlbum();
        }else {
            //申请权限
            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PICTURE_LIB_PERMISSION);
        }
    }

    public void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        Log.d(TAG, "openPictureLib: 成功打开相册");
        //根据activity指定的那个Activity中回调。在ChatActivity中发生回调，调用onActivityResult()方法
        activity.startActivityForResult(intent, FROM_PICTURE_LIB);
    }

    //打开相机
    public void openCamera(){
        //检查权限
        if(ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
            //执行拍照
            doTake();
        }else {
            //申请权限
            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.CAMERA},CAPTURE_PERMISSION);
        }
    }
    //执行拍照的方法
    public void doTake() {
        //创建一个文件，用于保存图片
        pictureFile = new File(activity.getExternalCacheDir(),"imageOut.jpeg");
        if (pictureFile.exists())
            pictureFile.delete();
        try {
            pictureFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取图片的uri
        if (Build.VERSION.SDK_INT > 24) {
            //当SDK版本大于24，则采用ContentProvider获取
            pictureUri = FileProvider.getUriForFile(activity,"com.zy.dingdong.fileprovider",pictureFile);
        }else {
            pictureUri = Uri.fromFile(pictureFile);
        }
        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        activity.startActivityForResult(intent,FROM_CAMERA);
    }

    //从图库中获取图片路径
    public  String getRealPathFromUri(Context context, Uri uri) {
        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion >= 19) {
            //API版本大于19
            return getRealPathFromUriAboveApi19(context, uri);
        } else {
            //API版本小于19，通过ContentProvider获取
            return getRealPathFromUriBelowAPI19(context, uri);
        }
    }
    private String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
        return getDataColumn(context, uri, null);
    }

    private String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        //解析uri
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) {
                // 使用':'分割
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if (isDownloadsDocument(uri)) {
                //对msf开头的id进行特殊处理
                if (documentId != null && documentId.startsWith("msf:")){
                    filePath = removeMSFContent(context, uri);
                }else {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                    filePath = getDataColumn(context, contentUri, null);
                }
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null);
        } else if ("file".equals(uri.getScheme())) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.getPath();
        }
        return filePath;
    }

    public String removeMSFContent(Context context, Uri uri) {
        File file = new File(context.getCacheDir(),"temp_file" + context.getContentResolver().getType(uri).split("/")[1]);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            OutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4*1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0, read);
            }
            outputStream.flush();
            return file.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    //在API19以前，可以通过ContentProvider拿到图片的路径
    private String getDataColumn(Context context, Uri uri, String selection) {
        String path = null;
        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }
    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
    private boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
    //通过Glide4 获取网络图片的长宽高并进行分类，分为横向图片，纵向图片，正方形
    public static int getPictureType(String url,Activity activity){
        int type;
        final int[] width=new int[1];
        final int[] height=new int[1];
        Glide.with(activity)
                .asBitmap()
                .load(url)//强制Glide返回一个Bitmap对象
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        width[0]= resource.getWidth();
                        height[0]= resource.getHeight();
                    }
                });
        int x=width[0]/2;
        if (0.9<x && x<1.11111){
            type=SQUARE_PICTURE;
        }else if ((width[0] - height[0]) > 0){
            type=HORIZONTAL_PICTURE;
        }else{
            type=VERTICAL_PICTURE;
        }
        return type;
    }

    //在活动回调数据中调用即可
    public void showPicture(int requestCode, int resultCode, @Nullable Intent data, Activity activity, ImageView imageView){
        Log.d(TAG, "PictureUtil.showPicture(): 调用回调方法后执行图片的显示");
        switch (requestCode) {
            case PictureUtil.FROM_CAMERA: {
                if (resultCode == activity.RESULT_OK) {
                    //将图片加载到头像框
                    Glide.with(activity)
                            .load(pictureUri)
                            .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .into(imageView);
                }
                break;
            }
            //图片来自相册，将图片加载到头像框
            case PictureUtil.FROM_PICTURE_LIB: {
                String path = getRealPathFromUri(activity, data.getData());
                pictureFile = new File(path);
                if (getPictureFile() == null)
                    Log.d(TAG, "showPicture: 加载了图片，但图片是空的-----");
                Glide.with(activity)
                        .load(path)
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(imageView);
                break;
            }
            default:
                break;
        }
    }
}
